import json

import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi import status
from fastapi.responses import JSONResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from linux.work_flow import *

app = FastAPI()


class findItem(BaseModel):
    mode: str
    data: str
    # 抽取视频的条数
    video_total: int
    # 每条视频抽取的评论数
    comment_total: int
user_id = ""
video_id_arr=[]
user_fs=""
user_like=""
user_name=""
video_total=0,
comment_total=0
@app.post("/get_video/")
async def get_video_context(form: findItem):
    global user_id, video_id_arr, user_fs, user_like, user_name,video_total,comment_total
    print("get_video()")
    user_id = get_user_id(form.data)
    video_total,comment_total,video_id_arr, user_fs, user_like, user_name, img_arr, img_text_arr, url_arr, like_arr = get_video_arr(user_id,form.video_total,form.comment_total)
    if not video_id_arr:
        return JSONResponse(
            status_code=status.HTTP_404_NOT_FOUND,
            content={
                'code': 404,
                "message":"fail"
            }
        )
    return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={
            'code': 200,
            'img_arr': img_arr,
            'img_text_arr': img_text_arr,
            "url_arr": url_arr,
            "like_arr": like_arr
        }
    )


@app.post("/analyst_data/")
async def analyst_data(form: findItem):
    print("开始analyst_data（）")
    global user_id, video_id_arr, user_fs, user_like, user_name,video_total,comment_total

    # 判断是否分析过这个id
    folder_path = "./linux/json/"  # 替换为您的文件夹路径
    target_string = "" + user_id + ".json"  # 替换为您要查找的字符串
    if check_file_exists(folder_path, target_string):
        with open(folder_path + target_string, 'r', encoding='utf-8') as file:
            data = json.load(file)
        return JSONResponse(
            status_code=status.HTTP_200_OK,
            content=data
        )
    else:
        if not video_id_arr:
            return JSONResponse(
                status_code=status.HTTP_400_BAD_REQUEST,
                content={
                    'code': 400,
                    'message': "此人无视频，暂时无法分析"
                })
        requerst_tiktok(video_id_arr, 50, comment_total, user_name)
        data_preprocessing(user_name)
        drew_wordcloud(user_name)
        get_label(user_name)
        load_linux_spark()

        # 评论人数最多的省，最大的省份的人数百分比，年,按年的白子数，按年的黑子数,时间热力图，总体白子黑子饼图1，2,各省的数据展示
        hour_max_count, hour_max, max_weekday, max_weekday_pair, province, province_max, year_arr, result1, result2, result4_date_count, value1, value2, province_top7, province_top7_value1, province_top7_value2, province_top7_revenue, province_top7_expenditures = out_to_front()
        content = {
            'code': 200,
            'message': "Success",
            'mode': form.mode,
            'input_text': form.data,
            'user_name': user_name,
            'user_id': user_id,
            'total': value1 + value2,
            'user_like': user_like,
            'user_fs': user_fs,
            'hour_max': hour_max,
            'hour_max_count_pair': (int((hour_max_count / (value1 + value2)) * 10000)) / 100,
            'max_weekday': max_weekday,
            'max_weekday_pair': max_weekday_pair,
            'province': {
                "province": province[0],
                "province_max": province_max,
            },
            'pie': {
                "value1": value1,
                "value2": value2,
            },
            'pie_cal': {
                "date": year_arr,
                "value1": result1.tolist(),
                "value2": result2.tolist()
            },
            "cal": result4_date_count,
            "bar_line": {
                "province_top7": province_top7,
                "province_top7_value1": province_top7_value1,
                "province_top7_value2": province_top7_value2,
                "province_top7_revenue": province_top7_revenue,
                "province_top7_expenditures": province_top7_expenditures
            }
        }

        # 将列表转换为JSON字符串
        json_data = json.dumps(content, ensure_ascii=False, indent=4)
        # 将JSON字符串写入到文件中
        with open('./linux/json/' + user_id + '.json', 'w', encoding='utf-8') as f:
            f.write(json_data)

        # 删除out1,2的csv文件

        # 创建待办事项的逻辑
        return JSONResponse(
            status_code=status.HTTP_200_OK,
            content=content
        )


@app.post("/todos/")
async def create_todo():
    # 创建待办事项的逻辑
    return "todo_id"


if __name__ == '__main__':
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    uvicorn.run(app)
